<template>
  <el-container class="container">
    <el-header>
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="groupFilterText"
        clearable
      >
      </el-input>
    </el-header>
    <el-main class="nopadding">
      <div class="query-tree-side-scroll">
        <el-scrollbar>
          <el-tree
            ref="group"
            class="menu"
            empty-text="未创建数据源连接"
            node-key="id"
            :data="tree.groupData"
            :current-node-key="''"
            :highlight-current="true"
            :expand-on-click-node="false"
            :default-expanded-keys="tree.defualtExpendedKeys"
            :filter-node-method="groupFilterNode"
            :props="tree.defaultProps"
          >
            <template #default="{ node }">
              <span
                @dblclick="dbClient(node)"
                class="custom-tree-node menus"
                @contextmenu="contextMenuClick(node, $event)"
              >
                <el-icon :style="iconStyleObject(node)"
                  ><dbant-icon :icon="getIcon(node)"
                /></el-icon>
                <span> {{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-main>
  </el-container>
  <vue3-menus v-model:open="isOpen" :event="eventVal" :menus="menus" hasIcon>
    <template #icon="{ item: { activeIndex } }">{{ activeIndex }}</template>
    <template #label="{ item: { item } }">{{ item.label }}</template>
  </vue3-menus>
  <component
    v-if="pluginComponentVisible"
    :is="contextMenuComponent"
    v-bind="contextMenuComponentData"
    v-model:pluginComponentVisible="pluginComponentVisible"
  ></component>
</template>

<script>
import { defineAsyncComponent, ref, nextTick } from "vue";
import { QueryTab } from "@/components/QueryTab";
import {remove} from 'lodash'
export default {
  name: "QueryResource",
  props: {
    queryTabs: Object,
  },

  data() {
    return {
      offset: 0.4,
      groupFilterText: "",
      tree: {
        groupData: [],
        defaultProps: {
          id: "id",
          children: "children",
          label: "name",
          isLeaf: "leaf",
        },
        defualtExpendedKeys: [],
        node: {},
      },
      search: {
        keyword: "",
      },
      rightMenuVisible: false,
      rightMenuComponent: null,
      rightMenu: ref(),
      isOpen: true,
      eventVal: {},
      menus: ref([]),
      contextMenuComponent: null,
      contextMenuComponentData: null,
      pluginComponentVisible: ref(false),
    };
  },
  watch: {
    groupFilterText(val) {
      this.$refs.group.filter(val);
    },
  },
  computed: {
    iconStyleObject: () => {
      return (node) => {
        if (node.data.type === "CONN") {
          let color = node.childrenLoaded ? "#165EFF" : "#8a8a8a";
          return `color:` + color + `;margin-right:2px`;
        }
        return `color:#165EFF;margin-right:2px`;
      };
    },
  },
  mounted() {
    this.$CONFIG.LOADED_CONN_IDS.length=0;
    console.log("初始数据："+this.$CONFIG.LOADED_CONN_IDS);
    this.$API.connection.getTree().then((res) => {
      this.tree.groupData = res.data;
    });
    this.$bus.$on(this.$CONFIG.REFRESH_NODE, (node) => {
      this.dbClient(node);
    });
    this.$bus.$on(this.$CONFIG.DELETE_NODE_CHILDREN, (node) => {
      node.childrenLoaded = false;
      node.data.children = [];
      if(node.data.type==='CONN'){
        remove( this.$CONFIG.LOADED_CONN_IDS,function(n){
            return n===node.data.properties.connId;
        })
        console.log("删除数据："+this.$CONFIG.LOADED_CONN_IDS);
      }
  
    });
    this.$bus.$on(this.$CONFIG.REFRESH_NODE, (node) => {
      this.dbClient(node);
    });
    this.$bus.$on(
      this.$CONFIG.CONTEXT_MENU_EVENT_KEY,
      ({
        type = this.$CONFIG.CONTEXT_MENU_TYPE_DIALOG,
        title,
        id,
        component,
        data,
      }) => {
        this.contextMenuComponent = null;
        this.contextMenuComponentData = null;
        this.pluginComponentVisible = false;
        if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_DIALOG)) {
          this.pluginComponentVisible = true;
          this.contextMenuComponentData = data;
          this.contextMenuComponent = component;
        }
        if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_TAGS_COM)) {
          console.log(this.queryTabs);
          this.queryTabs.addTab(
            new QueryTab({
              title: title,
              id: id ? id : this.node.data.id + "_" + new Date(),
              type: "CONTEXT_MENU_TYPE_TAGS_COM",
              //  componentName: component,
              componentName: "SqlEditor",
              data: data,
            })
          );
          // this.queryTabs.addTab(
          //   new QueryTab({
          //     title: "路由3",
          //     id: "Home3",
          //     type: "CONTEXT_MENU_TYPE_TAGS_COM",
          //     componentName: "Home1",
          //     data: {
          //       test: "这是测试数据",
          //     },
          //   })
          // );
        }

        if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_TAGS_ROUTER)) {
          this.contextMenuComponentData = data;
          this.contextMenuComponent = component;
        }
        if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_ROUTER)) {
          this.contextMenuComponentData = data;
          this.contextMenuComponent = component;
        }
      }
    );
  },
  methods: {
    getIcon(node) {
      const pluginJs = this.$CONFIG.PLUGINS[node.data.properties.pluginId];
      if (!pluginJs) {
        return "";
      }
      const typeObj = pluginJs.resource[node.data.type.toLowerCase()];
      if (typeObj && typeObj.icon) {
        return pluginJs.resource[node.data.type.toLowerCase()].icon;
      }
      return node.data.type;
    },
    contextMenuClick(node, event) {
       const pluginJs =   this.$CONFIG.PLUGINS[node.data.properties.pluginId];
       this.menus =[];
       if(pluginJs&&pluginJs.resource[
        node.data.type.toLowerCase()
      ]){
        this.menus = pluginJs.resource[
        node.data.type.toLowerCase()
      ].contextMenu({ node: node });
       }
      this.isOpen = false;
      nextTick(() => {
        this.eventVal = event;
        this.isOpen = true;
      });
      event.preventDefault();
    },

    dbClient(node) {
      //判断如果已经加载过数据了，那么就不再进行加载数据
      if (
        !node.data ||
        !node.data.properties ||
        node.data.leaf ||
        node.childrenLoaded
      ) {
        //未展开就进行展开
        if (!node.expanded) {
          node.expanded = true;
        } else {
          node.expanded = false;
        }
        return;
      }
      //开启加载如表
      node.loading = true;
      const { connId, catalog, tableName } = node.data.properties;
      const params = { connId, catalog, tableName };
      //请求后台获取子节点数据
      this.$API.metadata
        .executeFunction({
          type: node.data.type,
          pluginId: node.data.properties.pluginId,
          params: params,
        })
        .then((res) => {
          //没有数据就设置空数据
          if (!res.data) {
            this.$set(node.data, "children", []);
          }
          node.data.children = res.data;
          //设置已经加载过的标识
          node.childrenLoaded = true;
          this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
          console.log("添加数据："+this.$CONFIG.LOADED_CONN_IDS);
          //展开
          node.expanded = true;
        })
        .finally(() => {
          //关闭加载图标
          node.loading = false;
        });
      // data.children.push(newChild);
      //   this.$refs.group.updateKeyChildren(node.id, res.data);
      //   this.tree.defualtExpendedKeys = [node.id];
      //   this.$refs.group.setCurrentKey(node.id);
      // });
    },
    //树过滤
    groupFilterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleCommand(command) {
      if (command == "closeConn") {
        this.tree.node.childrenLoaded = false;
        this.tree.node.data.children = [];
      }
      if (command == "openConn") {
        this.dbClient(this.tree.node);
      }
    },
    async openMenu(node, e) {
      this.tree.node = node;
      this.rightMenuComponent = defineAsyncComponent(
        this.$CONFIG.PLUGINS[this.tree.node.data.properties.pluginId].rightMenu
          .conn.component
      );
      await nextTick();
      this.rightMenuVisible = true;

      this.$refs.rightMenu.openMenu(node, e); // 方法2:直接调用
    },

    visibleChange(visible) {
      if (!visible) {
      }
    },
    getRightMenuCommpoent() {
      this.rightMenuComponent =
        this.$CONFIG.PLUGINS[
          this.tree.node.data.properties.pluginId
        ].rightMenu.CONN;

      return this.rightMenuComponent;
    },
    //树点击事件
    groupClick(data) {
      var params = {
        groupId: data.id,
      };
      this.$refs.table.reload(params);
    },
    //搜索
    upsearch() {
      this.$refs.table.upData(this.search);
    },
  },
};
</script>

<style  scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  height: 36px;
  padding-right: 10px;
}

.container {
  /*双击文字、input等，出现的蓝色底色，如何去除*/
  -moz-user-select: none;
  /*火狐*/
  -webkit-user-select: none;
  /*webkit浏览器*/
  -ms-user-select: none;
  /*IE10*/
  /*-khtml-user-select:none;!*早期浏览器*!*/
  user-select: none;
}

.query-tree-side-scroll {
  overflow: auto;
  overflow-x: hidden;
  height: 100%;
  flex: 1;
}
</style>
